class Commond {
  constructor() {
    this.saveTime = 120;
  }

  sendPos() {
    const haslocation = uni.getStorageSync("location");
    const storeUserInfo = uni.getStorageSync("userInfo");
    if (haslocation && storeUserInfo.token) {
      const location = JSON.parse(haslocation);
      getApp()
        .$http.post("api/tool/pos", {
          lat: location.lat,
          lng: location.lng,
        })
        .then((res) => {
          // console.log(res);
        });
    }
  }

  imgurlreplace(arr) {
    var ret = [];
    for (let item of arr) {
      ret.push(item);
    }
    return ret;
  }

  getLocation_local() {
    const that = this;
    const haslocation = uni.getStorageSync("location");
    const newTime = new Date().getTime();

    return new Promise((resolve, reject) => {
      const getPos = function () {
        uni.getLocation({
          type: "wgs84",
          success: (res) => {
            const location = {
              lat: res.latitude,
              lng: res.longitude,
              time: newTime,
            };
            cc, JSON.stringify(location);
            resolve(location);
          },
          complete(e) {
            if (e.errMsg != "getLocation:ok") {
              const location = uni.getStorageSync("location");
              if (location) {
                resolve(JSON.parse(location));
              } else {
                console.log(e);
                reject(e);
              }
            }
          },
        });
      };

      if (haslocation) {
        const location = JSON.parse(haslocation);
        if (
          Math.ceil((newTime - location.time) / 1000) >= that.saveTime ||
          !location.time
        ) {
          getPos();
        } else {
          resolve(location);
        }
      } else {
        getPos();
      }
    });
  }

  getAddressForPosUser(rootUrl, lat, lng) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: rootUrl + "/technicianapp/index/getMapAddress",
        data: { location: `${lat},${lng}` },
        method: "POST",
        success: (res) => {
          resolve(res.data.data.result);
        },
      });
    });
  }

  getAddressForPosMap(rootUrl, lat, lng) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: rootUrl + "/technicianapp/index/getMapAddress",
        data: { location: `${lat},${lng}` },
        method: "POST",
        success: (res) => {
          resolve(res.data.data.result);
        },
				fail() {
					console.log('fail');
				}
      });
    });
  }

  getAddressForPos(rootUrl, lat, lng) {
    // console.log("rootUrl", rootUrl);
    return new Promise((resolve, reject) => {
      uni.request({
        url: rootUrl + "/technicianapp/index/getMapAddress",
        data: { location: `${lat},${lng}` },
        method: "POST",
        success: (res) => {
          console.log("getAddressForPos-res", res.data.data);
          resolve(res.data.data.result.address_component);
        },
      });
    });

    // return new Promise((resolve,reject)=>{
    // 	const script = document.createElement('script');
    // 	script.src = `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&output=jsonp&key=UP5BZ-4CYLM-NQM6W-665FE-UWNC7-PWF6J&callback=callback`;
    // 	const callbackName = 'callback';
    // 	window[callbackName] = function(data) {
    // 		document.body.removeChild(script);
    // 		delete window[callbackName];
    // 		if (data.status == 0) {
    // 			resolve(data.result.address_component);
    // 		} else {
    // 			resolve({});
    // 		}
    // 	};
    // 	document.body.appendChild(script);
    // });
  }

  getAddress() {
    return new Promise((resolve, reject) => {
      let getTxAddress = function (lat, lng) {
        const script = document.createElement("script");
        script.src = `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&output=jsonp&key=UP5BZ-4CYLM-NQM6W-665FE-UWNC7-PWF6J&callback=callbackaddress`;
        const callbackName = "callbackaddress";
        window[callbackName] = function (data) {
          document.body.removeChild(script);
          delete window[callbackName];
          if (data.status == 0) {
            let address = data.result.address_component || {};
            address["address"] = data.result.address || "";
            resolve(data.result.address_component);
          } else {
            resolve({});
          }
        };
        document.body.appendChild(script);
      };

      let localPos = uni.getStorageSync("location");
      if (localPos) {
        localPos = JSON.parse(localPos);
        getTxAddress(localPos.lat, localPos.lng);
        return;
      }

      this.getLocation()
        .then((res) => {
          getTxAddress(res.lat, res.lng);
        })
        .catch((err) => {
          reject(err);
          // uni.showModal({
          // 	title: "提示",
          // 	content: "您的地理位置获取异常，请您联系管理员解决"
          // });
        });
    });
  }

  ipLocation() {
    const newTime = new Date().getTime();
    return new Promise((resolve, reject) => {
      let getLoaction = function () {
        const script = document.createElement("script");
        script.src = `https://apis.map.qq.com/ws/location/v1/ip?output=jsonp&key=UP5BZ-4CYLM-NQM6W-665FE-UWNC7-PWF6J&callback=callbackip`;
        const callbackName = "callbackip";
        window[callbackName] = function (data) {
          document.body.removeChild(script);
          delete window[callbackName];
          if (data.status == 0) {
            const location = {
              lat: data.result.location.lat,
              lng: data.result.location.lng,
              time: newTime,
            };
            uni.setStorageSync("location", JSON.stringify(location));
            resolve(location);
          } else {
            reject(data);
          }
        };
        document.body.appendChild(script);
      };
      getLoaction();
    });
  }

  getLocation() {
    return new Promise((resolve, reject) => {
      const newTime = new Date().getTime();
      uni.request({
        url: "https://apis.map.qq.com/ws/location/v1/ip?key=UP5BZ-4CYLM-NQM6W-665FE-UWNC7-PWF6J",
        success: (res) => {
          // console.log("uni.request", res);
          const location = {
            lat: res.data.result.location.lat,
            lng: res.data.result.location.lng,
            time: newTime,
          };
          uni.setStorageSync("location", JSON.stringify(location));
          resolve(location);
        },
      });
    });
  }

  // getLocation(){
  // 	const that=this;
  // 	let timer=null;
  // 	return new Promise((resolve,reject)=>{
  // 		const haslocation=uni.getStorageSync('location');
  // 		const newTime = new Date().getTime();

  // 		let getIPLocation=function(from=null){
  // 			console.log('getIPLocation',from);
  // 			const script = document.createElement('script');
  // 			script.src = `https://apis.map.qq.com/ws/location/v1/ip?output=jsonp&key=UP5BZ-4CYLM-NQM6W-665FE-UWNC7-PWF6J&callback=callbackip`;
  // 			const callbackName = 'callbackip';
  // 			window[callbackName] = function(data) {
  // 				clearTimeout(timer);
  // 				document.body.removeChild(script);
  // 				delete window[callbackName];
  // 				if (data.status == 0) {
  // 					const location={"lat":data.result.location.lat,"lng":data.result.location.lng,"time":newTime};
  // 					uni.setStorageSync('location',JSON.stringify(location));
  // 					resolve(location);
  // 				} else {
  // 					reject(data);
  // 				}
  // 			};
  // 			document.body.appendChild(script);
  // 			timer && clearTimeout(timer);
  // 			timer = setTimeout(() => {
  // 				clearTimeout(timer);
  // 				reject(new Error('getIPLocation promise time out'));
  // 			}, 1500);

  // 		};

  // 		const getLocalPos=function(){
  // 			console.log('getLocalPos');

  // 			timer && clearTimeout(timer);
  // 			timer = setTimeout(() => {
  // 				clearTimeout(timer);
  // 				getIPLocation('timer');
  // 			}, 1500);

  // 			uni.getLocation({
  // 				type: 'wgs84',
  // 				success: (res) => {
  // 					const location={"lat":res.latitude,"lng":res.longitude,"time":newTime};
  // 					uni.setStorageSync('location',JSON.stringify(location));
  // 					resolve(location);
  // 				},
  // 				complete(e) {
  // 					clearTimeout(timer);
  // 					console.log('11111111',e);
  // 					if(e.errMsg!='getLocation:ok'){
  // 						const location=uni.getStorageSync('location');
  // 						if(location){
  // 							resolve(JSON.parse(location));
  // 						}else{
  // 							console.log('getLocalPos',e);
  // 							reject(e);
  // 						}
  // 					}
  // 				}
  // 			});
  // 		};

  // 		const getPos=function(){
  // 			console.log('getPos');
  // 			uni.request({
  // 				url: getApp().$base.baseUrl+'/api/Wechat/getSignpPackage', //请求后台接口获取权限验证配置参数
  // 				data: {
  // 					"url": window.location.href.split('#')[0]
  // 				},
  // 				method: 'POST',
  // 				timeout: 600000,
  // 				success: (res) => {

  // 				},
  // 				fail(err) {
  // 					getLocalPos('sign Error');
  // 					// reject(err);
  // 				}
  // 			});
  // 		};

  // 		if(haslocation){
  // 			const location=JSON.parse(haslocation);
  // 			if((Math.ceil((newTime - location.time) / 1000))>=that.saveTime || !location.time){
  // 				getPos();
  // 			}else{
  // 				resolve(location);
  // 			}
  // 		}else{
  // 			if(this.isWechat())
  // 				getPos();
  // 			else
  // 				getLocalPos('PC')
  // 		}
  // 	});
  // }

  isWechat() {
    var ua = navigator.userAgent.toLowerCase(); //获取判断用的对象
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
      return true;
    } else {
      return false;
    }
  }
}

export default Commond;
